package com.woniu.service.impl;

import com.woniu.entity.News;
import com.woniu.entity.NewsVO;
import com.woniu.service.NewsService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class NewsServiceImpl implements NewsService {
    @Resource
    private RedisTemplate redisTemplateInit;
    @Override
    public ResponseUtil addNews(NewsVO news) {
        News addNews = new News();
        addNews.setId(news.getId());
        addNews.setTitle(news.getTitle());
        Boolean add = redisTemplateInit.opsForZSet()
                .add("news", addNews, news.getVolume());
        return add == true ?
                ResponseUtil.get(ResponseEnum.OK,addNews)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil queryNews() {
        //排行榜需要排序 阅读量从大到小排序
        //使用redis中的ZREVRANGE命令
        //在redisTemplateInit中使用reverseRangeWithScores
        Set<NewsVO> news = redisTemplateInit.opsForZSet()
                .reverseRangeWithScores("news", 0, -1);
        List<NewsVO> newsList = news.stream().collect(Collectors.toList());
        return newsList.size() > 0 ?
                ResponseUtil.get(ResponseEnum.OK,newsList)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil addVolume(News news) {
        //点击一次 就提高分数
        Double incrementScore = redisTemplateInit.opsForZSet().incrementScore("news", news, 1);
        return incrementScore > 0 ?
                ResponseUtil.get(ResponseEnum.OK,news)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
}
